package cn.yunhe.servlet;

import cn.yunhe.entity.User;
import cn.yunhe.service.UserService;
import cn.yunhe.util.DateUtil;
import cn.yunhe.util.MD5;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName");
        String pwd =  request.getParameter("passWord");
        String md5 = MD5.encryptPassword(pwd,userName).toString();
        User user = new User(userName,md5);
        UserService userService = new UserService();
        user = userService.login(user);
        if (user!=null){//登陆成功
            if (user.getUserflag()==1){//管理员登录
                String datetime = DateUtil.getCurrTime();
                request.getSession().setAttribute("Curr_User",user);
                request.getSession().setAttribute("datetime",datetime);
                        response.sendRedirect("manage/index.jsp");
            }else{
            request.getSession().setAttribute("Curr_User",user);
            response.sendRedirect("GetProductServlet2");
			}
        }else{//登录失败
            String msg = "登录失败,请检查用户名和密码";
            request.setAttribute("denglushibai",msg);
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
